import React, { useImperativeHandle, forwardRef } from 'react';
import { isEmpty } from 'loadsh';
import PropTypes from 'prop-types';
import FormStoreContext from './FormStoreContext';
import FormStore from './FormStore';
import './form.css';

// Form 组件主要提供上下文
function Forms(props, ref) {
  const { children, onSubmit, onReset, defaultArrs, ruleArrs } = props;

  const store = new FormStore(
    defaultArrs || {}, // 表单初始值
    ruleArrs || {}
  );

  const Submit = (cb) => {
    if (isEmpty(store.validate())) {
      const data = store.get();
      cb(data);
      return;
    }
    // 验证失败
    cb(false);
  };

  const Reset = () => {
    store.reset();
  };

  // 暴露一些方法 让父组件使用 提交和重置 方法
  useImperativeHandle(ref, () => ({
    Submit,
    Reset,
  }));

  const defaultSubmit = (e) => {
    // 阻止表单默认行为
    e.preventDefault() || (e.returnValue = false);
    onSubmit(e);
  };

  return (
    <FormStoreContext.Provider value={store} ref={ref}>
      <form className={'agileh_ui_form'} onSubmit={defaultSubmit} onReset={onReset}>
        {children}
      </form>
    </FormStoreContext.Provider>
  );
}

// onSubmit, onReset, defaultArrs, ruleArrs
const Form = forwardRef(Forms);
Form.propTypes = {
  onSubmit: PropTypes.func,
  onReset: PropTypes.func,
  defaultArrs: PropTypes.object,
  ruleArrs: PropTypes.object,
};

export default Form;
